package com.daisuxia.risk.service;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.antgroup.zmxy.openplatform.api.DefaultZhimaClient;
import com.antgroup.zmxy.openplatform.api.FileItem;
import com.antgroup.zmxy.openplatform.api.ZhimaApiException;
import com.antgroup.zmxy.openplatform.api.request.ZhimaAuthInfoAuthorizeRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaAuthInfoAuthqueryRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCreditScoreGetRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCreditWatchlistiiGetRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaDataBatchFeedbackRequest;
import com.antgroup.zmxy.openplatform.api.response.ZhimaAuthInfoAuthqueryResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCreditScoreGetResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCreditWatchlistiiGetResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaDataBatchFeedbackResponse;
import com.daisuxia.back.utils.Assetdockingkd;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.lianlian.util.DateUtils;
import com.daisuxia.risk.pojo.FeedBackData;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.FTPUtil;
import com.daisuxia.risk.utils.GetHttp;
import com.daisuxia.risk.utils.WriteFTPFile;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.OrderNoUtil;

/**
 * 芝麻信用
 * 类描述：芝麻信用相关接口 <br>
 * 每次发出请求之前插入订单信息，返回后更新订单信息<br>
 * 此类不做任何业务处理，仅拼接参数请求第三方，必须使用trycath，并且不向上抛出异常以保证插入或更新的订单不会回滚<br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-12-12 下午03:41:28 <br>
 * 
 * @version
 * 
 */
@Service
public class ZmxyService implements IZmxyService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskOrdersService riskOrdersService;
	
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IUserService userService;
	
	private String BASE_URL="/files/zm_feedback/";
	private String FILE_DEPARTURE="/";

	@Override
	public ServiceResult getOpenId(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			if (userName != null && cardNum != null && userId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaAuthInfoAuthqueryRequest req = new ZhimaAuthInfoAuthqueryRequest();
				req.setIdentityType("2");// 必要参数
				/*********** 需要商户传递的参数 ***********/
				req.setIdentityParam("{\"certNo\":\"" + cardNum
						+ "\",\"certType\":\"IDENTITY_CARD\",\"name\":\""
						+ userName + "\"}");// 必要参数
				/*********** 需要商户传递的参数 ***********/
				DefaultZhimaClient client = new DefaultZhimaClient(zmUrl,
						appId, privateKey, zhimaPublicKey);
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_OPENID);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(req));
				logger.info("zm1 card"+cardNum);
//				logger.info("send to get openid " + orders.toString());
				riskOrdersService.insert(orders);
				ZhimaAuthInfoAuthqueryResponse response = client.execute(req);
//				logger.info("get openId response=" + response);
				if (response.isSuccess()) {
					if (response.getAuthorized()) {
						serviceResult = new ServiceResult(
								ServiceResult.SUCCESS, response.getOpenId());
					} else {
						serviceResult = new ServiceResult("100",
								"用户未授权，请发起授权请求！");
					}
				} else {
					serviceResult = new ServiceResult("300", response
							.getErrorMessage());
				}
				orders.setReturnParams(JSON.toJSONString(response));
				orders.setStatus(RiskOrders.STATUS_SUC);
				riskOrdersService.update(orders);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getOpenId error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult getURL(HashMap<String, Object> params,
			HttpServletRequest request) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			if (userName != null && cardNum != null && userId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaAuthInfoAuthorizeRequest req = new ZhimaAuthInfoAuthorizeRequest();
				req.setIdentityType("2");
				String channel = "apppc";
				String auth_code = "M_APPPC_CERT";
				String state = userId + "";
				if (GetHttp.isMobileDevice(request)) {
					channel = "app";
					auth_code = "M_H5";
				}
				// 必要参数 state: 用于给商户提供透传的参数，芝麻会将此参数透传给商户;
				req.setChannel(channel);
				req.setBizParams("{\"auth_code\":\"" + auth_code
						+ "\",\"state\":\"" + state + "\"}");
				// 必要参数
				req.setIdentityParam("{\"certNo\":\"" + cardNum
						+ "\",\"certType\":\"IDENTITY_CARD\",\"name\":\""
						+ userName + "\"}");
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_URL);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(req));
				logger.info("send to  getURL " + orders.toString());
				riskOrdersService.insert(orders);
				DefaultZhimaClient client = new DefaultZhimaClient(zmUrl,
						appId, privateKey, zhimaPublicKey);
				String url = client.generatePageRedirectInvokeUrl(req);
//				logger.info("get getAuthorizeUrl url=" + url);
				orders.setStatus(RiskOrders.STATUS_SUC);
				orders.setReturnParams(url);
				riskOrdersService.update(orders);
				serviceResult = new ServiceResult(ServiceResult.SUCCESS, url);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getURL error ,params=" + params, e);
		}
		return serviceResult;
	}
	@Override
	public ServiceResult getZmScore(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userId = params.get("userId");
			Object openId = params.get("openId");
			if (userId != null && openId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaCreditScoreGetRequest req2 = new ZhimaCreditScoreGetRequest();
				req2.setProductCode("w1010100100000000001");// 必要参数
				req2.setOpenId(openId + "");// 必要参数
				req2.setTransactionId(OrderNoUtil.getInstance().getUUID());
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_SCORE);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(req2));
				logger.info("zm2 userId"+userId);
//				logger.info("send to get openid " + orders.toString());
				riskOrdersService.insert(orders);
				DefaultZhimaClient client2 = new DefaultZhimaClient(zmUrl,
						appId, privateKey, zhimaPublicKey);
				ZhimaCreditScoreGetResponse response2 = client2.execute(req2);
//				logger.info("get score response=" + response2);
				if (response2.isSuccess()) {
					serviceResult = new ServiceResult(ServiceResult.SUCCESS,
							response2.getZmScore());
					orders.setStatus(RiskOrders.STATUS_SUC);
				} else {
					serviceResult = new ServiceResult("300", response2
							.getErrorMessage());
				}
				orders.setReturnParams(JSON.toJSONString(response2));
				riskOrdersService.update(orders);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getZmScore error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult getCreditWatchList(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userId = params.get("userId");
			Object openId = params.get("openId");
			if (userId != null && openId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaCreditWatchlistiiGetRequest creditWatchlistGetRequest = new ZhimaCreditWatchlistiiGetRequest();
				creditWatchlistGetRequest.setPlatform("zmop");
				creditWatchlistGetRequest.setChannel("apppc");
				creditWatchlistGetRequest.setTransactionId(OrderNoUtil
						.getInstance().getUUID());
				creditWatchlistGetRequest
						.setProductCode("w1010100100000000022");
				creditWatchlistGetRequest.setOpenId(openId + "");
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_INDUSTY);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON
						.toJSONString(creditWatchlistGetRequest));
				logger.info("zm3 userId"+userId);
//				logger.info("send getCreditWatchList " + orders.toString());
				riskOrdersService.insert(orders);
				DefaultZhimaClient client = new DefaultZhimaClient(zmUrl,
						appId, "utf-8", privateKey, zhimaPublicKey);
				ZhimaCreditWatchlistiiGetResponse response1 = client
						.execute(creditWatchlistGetRequest);
//				logger.info("getCreditWatchList response=" + response1);
				if (response1.isSuccess()) {
					orders.setStatus(RiskOrders.STATUS_SUC);
					serviceResult = new ServiceResult(ServiceResult.SUCCESS,
							JSON.toJSONString(response1));
				} else {
					serviceResult = new ServiceResult("300", response1
							.getErrorMessage());
				}
				orders.setReturnParams(JSON.toJSONString(response1));
				riskOrdersService.update(orders);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getCreditWatchList error ,params=" + params, e);
		}
		return serviceResult;
	}

	

	public void zhimaDataBatchFeedback() {
		logger.info("zhimaDataBatchFeedback start");
		
		Date yestodayDate = DateUtil.addDay(new Date(), -1);
    	logger.info( DateUtil.getDateFormat(yestodayDate,"yyyyMMdd"));
    	HashMap<String,Object> paraMap = new HashMap<String,Object>();
    	paraMap.put("yestoday", DateUtil.getDateFormat(yestodayDate,"yyyyMMdd"));
		
		List<BorrowOrder> assetBorrowOrderList = borrowOrderService.findAssetBorrowOrderForZhimaFeedback(paraMap);
		
		System.out.println("assetBorrowOrderList size:"+assetBorrowOrderList.size());
		
		if(null==assetBorrowOrderList || assetBorrowOrderList.isEmpty()){
			logger.info("no data to zhimaDataBatchFeedback");
			return;
		}
		List<FeedBackData> feedBackDatalist =  new ArrayList<FeedBackData>();
		
		for(BorrowOrder assetBorrowOrder : assetBorrowOrderList){
			FeedBackData feedBackData = this.searchBatchFeedBackData(assetBorrowOrder);
			if(null!=feedBackData){
				feedBackDatalist.add(feedBackData);
			}
		}
		
		if(null == feedBackDatalist || feedBackDatalist.isEmpty()){
			logger.info("no data to zhimaDataBatchFeedback");
			return ;
		}
		
		logger.info("feedBackDatalist size:"+feedBackDatalist.size());
		
		String zhimaDataJsonContent =  zhimaDataJsonContent(feedBackDatalist);
		
		logger.info("zhimaDataJsonContent:"+zhimaDataJsonContent);
		
		if(StringUtils.isBlank(zhimaDataJsonContent)){
			logger.info("no data to zhimaDataJsonContent");
			return ;
			
		}
		
		String fileSave = saveFileToLocal(zhimaDataJsonContent);
		
		logger.info("fileSave:"+fileSave);
		
		if(StringUtils.isNotBlank(fileSave)){
			zhimaDataBatchFeedback(fileSave);
		}
		
		logger.info("zhimaDataBatchFeedback end");
	}
	
	
	public void zhimaDataBatchFeedback(String fileSave) {
		logger.info("zhimaDataBatchFeedback start,fileSave:"+fileSave);
		
		String gatewayUrl = "https://zmopenapi.zmxy.com.cn/openapi.do";
		
		//Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.ZMXY);
		String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAP2kTM2/84qlLBNaRJliIwyMDw67wumr2C86r4Ihd9IiAhvXvtFf7jbW0+MfNJOYXOWCsJi+CCjxZmapcRVRP6eDbh+uppscYT7vRqZPGTUEw/KpKmU4LSGzeJeJsE26cENBPgLFHogLwbWVMzEY5CVRSEmFWFjxBo3L9D9/NiarAgMBAAECgYA3m227LfoWy19+XqvrdLh6Z7plYIS69hHPSO5xeSTrzMjpkcMj5AQ1waNyh8TfFuhG6QAOfJsNXt80YrGIGuf5QfvJfYFEtmIE9ysP24euCoSZxgEKgVWyOaHcybo+cVG0RHs5avlU+0ITRkNqTJlQll/4JHg5wUX9ctaSlNT+AQJBAP+ZWZFQLVntwfcZbfvEnm4N3lqVyTAKuoqc91NjpLcIGQxunD0XkcLNJTrWYxw5cbX1IoddvT+KEzyZ0YQK/PkCQQD+CioC6zMuqSprEARS6Tp4KSyifF5poKEK2hYHIuSsdJvXmUXsCmI/bAmlyfq+dJY/zgwdnbRTakGsExBFuV3DAkAaS1ZRgqQHulPX7b/IxMNfowGa5AncbV4fYGJ5K6kIQ0cAZmigSEpwddY8pU1w29/8zgkNT/FmFfhApbpOEStRAkBPkn92SpXNl89hmbLBBaz61mrUuoAYNeg7rfQYaCWYny3xamEsflQn6X9cHtgbsAkgEzpYTH2fYzkO3SnLrTRhAkEAlINu2KRpvIZlE/1L3FPN1KlC/m/d8XIqFR9vE1rFkfPKblfp9qm1tauCo6nUt9ffLArwWUGFlE/oKg+sO+C57Q==";// keys.get("zm_private_key");
		String zhimaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjgja2K4dS5Ac+vmy/tqpyHXiOZcIoGPI9kURQ7wb+qJe0VDufH1aovOALVBors48pYBtvzI9D81rqlD/prZ358rbkTDaTk/s027Zn/O827o1NbUnUxaWtINN36f5eGrpijGt49aC07a4vJyEOcefZ+RIOKA9GZLdT4IEhy8YWRQIDAQAB";// keys.get("zm_public_key");
		String appId =  "1001215";// keys.get("zm_appId");
		
        ZhimaDataBatchFeedbackRequest req = new ZhimaDataBatchFeedbackRequest();
        req.setPlatform("zmop");
        req.setFileType("json_data");// 必要参数        
        req.setFileCharset("UTF-8");// 必要参数        
        req.setRecords("1");// 必要参数        
        req.setColumns("user_name,user_credentials_type,user_credentials_no,order_no,biz_type,order_status,pay_month,gmt_ovd_date,create_amt,overdue_days,overdue_amt,gmt_pay,memo");// 必要参数        
        req.setPrimaryKeyColumns("order_no");// 必要参数        
        req.setFileDescription("文件描述信息");//        
        req.setTypeId("1001215-default-order");// 必要参数         1001215-default-test 
        req.setFile(new FileItem(fileSave));// 必要参数 
        
        DefaultZhimaClient client = new DefaultZhimaClient(gatewayUrl, appId, privateKey,zhimaPublicKey);
        try {
            ZhimaDataBatchFeedbackResponse response = client.execute(req);
            System.out.println(response.isSuccess());
            System.out.println(response.getErrorCode());
            System.out.println(response.getErrorMessage());
        } catch (ZhimaApiException e) {
            e.printStackTrace();
        }
		
		logger.info("zhimaDataBatchFeedback end");
		
	}
	
	
	public void zhimaDataBatchFeedback(FileItem jsonFile) {
		logger.info("zhimaDataBatchFeedback start,jsonFile:"+jsonFile);
		
		String gatewayUrl = "https://zmopenapi.zmxy.com.cn/openapi.do";
		
		//Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.ZMXY);
		String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAP2kTM2/84qlLBNaRJliIwyMDw67wumr2C86r4Ihd9IiAhvXvtFf7jbW0+MfNJOYXOWCsJi+CCjxZmapcRVRP6eDbh+uppscYT7vRqZPGTUEw/KpKmU4LSGzeJeJsE26cENBPgLFHogLwbWVMzEY5CVRSEmFWFjxBo3L9D9/NiarAgMBAAECgYA3m227LfoWy19+XqvrdLh6Z7plYIS69hHPSO5xeSTrzMjpkcMj5AQ1waNyh8TfFuhG6QAOfJsNXt80YrGIGuf5QfvJfYFEtmIE9ysP24euCoSZxgEKgVWyOaHcybo+cVG0RHs5avlU+0ITRkNqTJlQll/4JHg5wUX9ctaSlNT+AQJBAP+ZWZFQLVntwfcZbfvEnm4N3lqVyTAKuoqc91NjpLcIGQxunD0XkcLNJTrWYxw5cbX1IoddvT+KEzyZ0YQK/PkCQQD+CioC6zMuqSprEARS6Tp4KSyifF5poKEK2hYHIuSsdJvXmUXsCmI/bAmlyfq+dJY/zgwdnbRTakGsExBFuV3DAkAaS1ZRgqQHulPX7b/IxMNfowGa5AncbV4fYGJ5K6kIQ0cAZmigSEpwddY8pU1w29/8zgkNT/FmFfhApbpOEStRAkBPkn92SpXNl89hmbLBBaz61mrUuoAYNeg7rfQYaCWYny3xamEsflQn6X9cHtgbsAkgEzpYTH2fYzkO3SnLrTRhAkEAlINu2KRpvIZlE/1L3FPN1KlC/m/d8XIqFR9vE1rFkfPKblfp9qm1tauCo6nUt9ffLArwWUGFlE/oKg+sO+C57Q==";// keys.get("zm_private_key");
		String zhimaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjgja2K4dS5Ac+vmy/tqpyHXiOZcIoGPI9kURQ7wb+qJe0VDufH1aovOALVBors48pYBtvzI9D81rqlD/prZ358rbkTDaTk/s027Zn/O827o1NbUnUxaWtINN36f5eGrpijGt49aC07a4vJyEOcefZ+RIOKA9GZLdT4IEhy8YWRQIDAQAB";// keys.get("zm_public_key");
		String appId =  "1001215";// keys.get("zm_appId");
		
        ZhimaDataBatchFeedbackRequest req = new ZhimaDataBatchFeedbackRequest();
        req.setPlatform("zmop");
        req.setFileType("json_data");// 必要参数        
        req.setFileCharset("UTF-8");// 必要参数        
        req.setRecords("1");// 必要参数        
        req.setColumns("user_name,user_credentials_type,user_credentials_no,order_no,biz_type,order_status,pay_month,gmt_ovd_date,create_amt,overdue_days,overdue_amt,gmt_pay,memo");// 必要参数        
        req.setPrimaryKeyColumns("order_no");// 必要参数        
        req.setFileDescription("文件描述信息");//        
        req.setTypeId("1001215-default-test");// 必要参数        
        req.setFile(jsonFile);// 必要参数 
        
        DefaultZhimaClient client = new DefaultZhimaClient(gatewayUrl, appId, privateKey,zhimaPublicKey);
        try {
            ZhimaDataBatchFeedbackResponse response = client.execute(req);
            System.out.println(response.isSuccess());
            System.out.println(response.getErrorCode());
            System.out.println(response.getErrorMessage());
        } catch (ZhimaApiException e) {
            e.printStackTrace();
        }
		
		logger.info("zhimaDataBatchFeedback end");
		
	}
	
	public FeedBackData searchBatchFeedBackData(BorrowOrder borrowOrder) {
		logger.info("searchBatchFeedBackData start");
		try{
			
			
			if(null==borrowOrder){
				return null;
			}
			
			Integer userId = borrowOrder.getUserId();
			
			if(null==userId){
				logger.info("searchBatchFeedBackData userId is null");
				return null;
			}
			
			Map<String, String> userParaMap = new HashMap<String,String>();
			userParaMap.put("id", String.valueOf(userId));
			User user = userService.searchByInviteUserid(userParaMap);
			
			if(null== user){
				logger.info("searchBatchFeedBackData user is null,assetBorrowOrderId:"+borrowOrder.getId()+",userId:"+userId);
				return null;
			}
			
			if(StringUtils.isBlank(user.getIdNumber())){
				logger.info("searchBatchFeedBackData user idnumer is null,assetBorrowOrderId:"+borrowOrder.getId()+",userId:"+userId);
				return null;
			}
			
			if(StringUtils.isBlank(user.getRealname())){
				logger.info("searchBatchFeedBackData user realname is null,assetBorrowOrderId:"+borrowOrder.getId()+",userId:"+userId);
				return null;
			}
			
			if(null==borrowOrder.getLoanEndTime()){
				logger.info("searchBatchFeedBackData borrowOrder loanEndtime is null");
				return null;
			}
			
			if(null==borrowOrder.getLoanTime()){
				logger.info("searchBatchFeedBackData borrowOrder loantime is null");
				return null;
			}
			FeedBackData feedBackData = new FeedBackData();
			feedBackData.setUserCredentialsType(Constant.FEED_BACK_DATA_ID_TYPE);
			feedBackData.setUserCredentialsNo(user.getIdNumber());
			feedBackData.setUserName(user.getRealname());
			feedBackData.setOrderNo(String.valueOf(borrowOrder.getId()));
			feedBackData.setBizType(Constant.FEED_BACK_DATA_BIZ_TYPE);
			feedBackData.setOrderStatus(Constant.ZM_FEED_BACK_ORDER_STATUS.get(String.valueOf(borrowOrder.getStatus())));
			feedBackData.setPayMonth(payMonth(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setGmtOvdDate(gmtOverDate(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setCreateAmt(createAmnt(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setOverDueDays(overDueDays(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setOverdueAmt(overDueAmt(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setGmtPay(gmtPay(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setMemo("");
			
			logger.info("searchBatchFeedBackData end,assetBorrowOrderId:"+borrowOrder.getId());
			
			return feedBackData;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}


	public FeedBackData searchBatchFeedBackData(String assetBorrowOrderId) {
		logger.info("searchBatchFeedBackData start,assetBorrowOrderId:"+assetBorrowOrderId);
		try{
			
			BorrowOrder borrowOrder = borrowOrderService.findOneBorrow(Integer.valueOf(assetBorrowOrderId));
			
			if(null==borrowOrder){
				logger.info("searchBatchFeedBackData borrowOrder is null,assetBorrowOrderId:"+assetBorrowOrderId);
				return null;
			}
			
			Integer userId = borrowOrder.getUserId();
			
			Map<String, String> userParaMap = new HashMap<String,String>();
			userParaMap.put("id", String.valueOf(userId));
			User user = userService.searchByInviteUserid(userParaMap);
			
			if(null== user){
				logger.info("searchBatchFeedBackData user is null,assetBorrowOrderId:"+assetBorrowOrderId+",userId:"+userId);
				return null;
			}
			
			if(StringUtils.isBlank(user.getIdNumber())){
				logger.info("searchBatchFeedBackData user idnumer is null,assetBorrowOrderId:"+assetBorrowOrderId+",userId:"+userId);
				return null;
			}
			
			if(StringUtils.isBlank(user.getRealname())){
				logger.info("searchBatchFeedBackData user realname is null,assetBorrowOrderId:"+assetBorrowOrderId+",userId:"+userId);
				return null;
			}
			
			if(null==borrowOrder.getLoanEndTime()){
				return null;
			}
			
			if(null==borrowOrder.getLoanTime()){
				return null;
			}
			FeedBackData feedBackData = new FeedBackData();
			feedBackData.setUserCredentialsType(Constant.FEED_BACK_DATA_ID_TYPE);
			feedBackData.setUserCredentialsNo(user.getIdNumber());
			feedBackData.setUserName(user.getRealname());
			feedBackData.setOrderNo(assetBorrowOrderId);
			feedBackData.setBizType(Constant.FEED_BACK_DATA_BIZ_TYPE);
			feedBackData.setOrderStatus(Constant.ZM_FEED_BACK_ORDER_STATUS.get(String.valueOf(borrowOrder.getStatus())));
			feedBackData.setPayMonth(payMonth(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setGmtOvdDate(gmtOverDate(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setCreateAmt(createAmnt(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setOverDueDays(overDueDays(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setOverdueAmt(overDueAmt(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setGmtPay(gmtPay(feedBackData.getOrderStatus(),borrowOrder));
			feedBackData.setMemo("");
			
			logger.info("searchBatchFeedBackData end,assetBorrowOrderId:"+assetBorrowOrderId);
			
			return feedBackData;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	
	}
	
	public String zhimaDataJsonContent(List<FeedBackData> list) {
		Map<String,Object> records = new HashMap<String,Object>();
		
		List<Map<String,Object>> recordlist = new ArrayList<Map<String,Object>>();
		
		if(null==list || list.size()==0){
			return "";
		}
		
		for(FeedBackData feedBackData : list){
			
			Map<String,Object> oneRecord = new HashMap<String,Object>();
			
			oneRecord.put("user_credentials_no", feedBackData.getUserCredentialsNo());
			oneRecord.put("biz_type", feedBackData.getBizType());
			oneRecord.put("gmt_pay", feedBackData.getGmtPay());
			oneRecord.put("memo", feedBackData.getMemo());
			oneRecord.put("user_credentials_type",feedBackData.getUserCredentialsType());
			oneRecord.put("pay_month", feedBackData.getPayMonth());
			oneRecord.put("order_no", feedBackData.getOrderNo());
			oneRecord.put("order_status", feedBackData.getOrderStatus());
			oneRecord.put("user_name", feedBackData.getUserName());
			oneRecord.put("overdue_days", feedBackData.getOverDueDays());
			oneRecord.put("overdue_amt", feedBackData.getOverdueAmt());
			oneRecord.put("gmt_ovd_date", feedBackData.getGmtOvdDate());
			oneRecord.put("create_amt", feedBackData.getCreateAmt());
			
			recordlist.add(oneRecord);
			
		}
		records.put("records", recordlist);	
		
		return JSONUtil.beanToJson(records);
	}
	
	
	private String payMonth(String orderStatus,BorrowOrder borrowOrder){
		if("01".equals(orderStatus) || "02".equals(orderStatus) || "03".equals(orderStatus)){
			return "";
		}else{
			return "O";
		}
	}
	
	private String gmtOverDate(String orderStatus,BorrowOrder borrowOrder) throws ParseException{
		if("01".equals(orderStatus) || "02".equals(orderStatus) || "03".equals(orderStatus)){
			return DateUtil.getDateFormat(borrowOrder.getUpdatedAt(),"yyyy-MM-dd"); 
		}else{
			if(DateUtil.daysBetween(new Date(), borrowOrder.getLoanEndTime())<0){
				return DateUtil.getDateFormat(borrowOrder.getLoanTime(),"yyyy-MM-dd"); 
			}else{
				return DateUtil.getDateFormat(borrowOrder.getLoanEndTime(),"yyyy-MM-dd");
			}
		}
	}
	
	private String createAmnt(String orderStatus,BorrowOrder borrowOrder){
		return String.valueOf(borrowOrder.getMoneyAmount()/100);
	}
	
	private String overDueDays(String orderStatus,BorrowOrder borrowOrder) throws ParseException{
		if("01".equals(orderStatus) || "02".equals(orderStatus) || "03".equals(orderStatus)){
			return "";
		}else{
			if(-11==borrowOrder.getStatus().intValue() || 34==borrowOrder.getStatus().intValue()){
				return String.valueOf(DateUtil.daysBetween(borrowOrder.getLoanEndTime(),new Date()));
			}else{
				return "0";
			}
		}
	}
	
	private String overDueAmt(String orderStatus,BorrowOrder borrowOrder){
		if("01".equals(orderStatus) || "02".equals(orderStatus) || "03".equals(orderStatus)){
			return "";
		}else{
			if(-11==borrowOrder.getStatus().intValue() || 34==borrowOrder.getStatus().intValue()){
				return String.valueOf(borrowOrder.getMoneyAmount());
			}else{
				return "0";
			}
		}
	}
	
	private String gmtPay(String orderStatus,BorrowOrder borrowOrder){
		if("04".equals(orderStatus) &&  (30 == borrowOrder.getStatus().intValue() || 34==borrowOrder.getStatus().intValue())){
			return DateUtil.getDateFormat(borrowOrder.getUpdatedAt(),"yyyy-MM-dd");
		}else{
			return "";
		}
	}

	
	private void uploadToFtp(String jsonContent){
		Date nowDate = new Date();
		String dateStr = DateUtil.getDateFormat(nowDate,"yyyyMMddHHmmss");
		int ftpPort = 0;  
        String ftpUserName = "";  
        String ftpPassword = "";  
        String ftpHost = "";  
        String ftpPath = "";  
        String writeTempFielPath = "";  
        String ftpPath2 = "";
        try {  
            ftpUserName = "ftpuser";  
            ftpPassword = "pwd123@";  
            ftpHost = "192.168.1.124";  
            ftpPort = 21;
              
            ftpPath2 = "/feedback/"+dateStr ;
            
            ftpPath = ftpPath2+"/"+dateStr+".json";
            
            WriteFTPFile write = new WriteFTPFile();  

            write.upload(ftpPath2,ftpPath, ftpUserName, ftpPassword, ftpHost, ftpPort, jsonContent, writeTempFielPath);  
            
    } catch (Exception e) {  
            e.printStackTrace();  
        } 
	}

	public String saveFileToLocal(String fileContent) {
		 FileOutputStream fos = null;
	   	 OutputStreamWriter osw = null;
	   	 String fileName = DateUtils.getCurrentDateAndTime()+".json";
	   	 String filePath = BASE_URL+DateUtils.getCurrentDate()+FILE_DEPARTURE;
	   	 try{
	   		 	File dirFile = new File(filePath);
	   		 	if(!dirFile.exists()){
	   		 		dirFile.mkdirs();
	   		 	}
	   	        File file = new File(filePath+fileName);
	   	        fos = new FileOutputStream(file);   
	   	        osw = new OutputStreamWriter(fos, "UTF-8");   
	   	        osw.write(fileContent);   
	   	        osw.flush();
	   	     return filePath+fileName;
	   	}catch(Exception e){
	   		e.printStackTrace();
	   		return "";
	   	}finally{
	   		if(null!=fos){
	   			try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	   		}
	   		if(null!=osw){
	   			try {
						osw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	   		}
	   		
	   	}
		}

}
